package com.example.ivideo_2211a

import android.Manifest
import android.content.pm.PackageManager
import android.hardware.Camera
import android.media.CamcorderProfile
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.MotionEvent
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.ivideo_2211a.databinding.ActivityTakeBinding
import com.example.ivideo_2211a.take.PublishState
import com.example.ivideo_2211a.take.RecordingState
import com.example.ivideo_2211a.take.VideoPublishViewModel
import com.example.ivideo_2211a.take.VideoRecorderConfig
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

@Route(path = "/take/TakeActivity")
class TakeActivity : AppCompatActivity(), SurfaceHolder.Callback {
    
    private lateinit var binding: ActivityTakeBinding
    private val viewModel: VideoPublishViewModel by viewModels()
    
    // 相机相关
    private var camera: Camera? = null
    private var mediaRecorder: MediaRecorder? = null
    private var isRecording = false
    private var recordingStartTime = 0L
    private var outputFile: File? = null
    
    private val handler = Handler(Looper.getMainLooper())
    private val recordingRunnable = object : Runnable {
        override fun run() {
            if (isRecording) {
                updateRecordingTime()
                handler.postDelayed(this, 1000)
            }
        }
    }
    
    companion object {
        private const val CAMERA_PERMISSION_REQUEST = 100
        private const val RECORD_AUDIO_PERMISSION_REQUEST = 101
        private const val WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST = 102
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityTakeBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        setupWindowInsets()
        setupViews()
        observeViewModel()
        checkPermissions()
    }
    
    private fun setupWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }
    
    private fun setupViews() {
        // 设置SurfaceView的回调
        binding.cameraPreview.holder.addCallback(this)
        
        // 设置录制按钮的触摸事件
        binding.recordButtonContainer.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    startRecording()
                    true
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    stopRecording()
                    true
                }
                else -> false
            }
        }
        
        // 设置发布按钮点击事件
        binding.publishButton.setOnClickListener {
            showPublishDialog()
        }
        
        // 显示设备支持的录制质量
        showAvailableQualities()
    }
    
    private fun showAvailableQualities() {
        val availableQualities = VideoRecorderConfig.getAvailableQualities()
        val qualityText = "支持的录制质量: ${availableQualities.joinToString(", ")}"
        Log.d("TakeActivity", qualityText)
        
        // 可以在UI上显示这个信息，或者只在日志中显示
        // binding.qualityInfoText.text = qualityText
    }
    
    private fun observeViewModel() {
        lifecycleScope.launch {
            viewModel.recordingState.collect { state ->
                updateRecordingUI(state)
            }
        }
        
        lifecycleScope.launch {
            viewModel.publishState.collect { state ->
                updatePublishUI(state)
            }
        }
    }
    
    override fun surfaceCreated(holder: SurfaceHolder) {
        // Surface创建后初始化相机
        initializeCamera()
    }
    
    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        // Surface尺寸改变时重新配置相机
        if (holder.surface == null) return
        
        try {
            camera?.stopPreview()
        } catch (e: Exception) {
            // 忽略异常
        }
        
        try {
            camera?.setPreviewDisplay(holder)
            camera?.startPreview()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    override fun surfaceDestroyed(holder: SurfaceHolder) {
        // Surface销毁时释放相机
        releaseCamera()
    }
    
    private fun initializeCamera() {
        try {
            // 获取前置摄像头（如果有的话，否则使用后置摄像头）
            val cameraId = getFrontCameraId()
            camera = Camera.open(cameraId)
            
            // 设置相机参数
            val parameters = camera?.parameters
            parameters?.let {
                // 设置预览尺寸
                val previewSizes = it.supportedPreviewSizes
                if (previewSizes.isNotEmpty()) {
                    val previewSize = previewSizes[0] // 使用第一个支持的尺寸
                    it.setPreviewSize(previewSize.width, previewSize.height)
                }
                
                // 设置对焦模式（如果支持）
                val focusModes = it.supportedFocusModes
                if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                    it.focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO
                } else if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                    it.focusMode = Camera.Parameters.FOCUS_MODE_AUTO
                }
                
                // 设置白平衡（如果支持）
                val whiteBalanceModes = it.supportedWhiteBalance
                if (whiteBalanceModes.contains(Camera.Parameters.WHITE_BALANCE_AUTO)) {
                    it.whiteBalance = Camera.Parameters.WHITE_BALANCE_AUTO
                }
                
                // 设置场景模式（如果支持）
                val sceneModes = it.supportedSceneModes
                if (sceneModes.contains(Camera.Parameters.SCENE_MODE_ACTION)) {
                    it.sceneMode = Camera.Parameters.SCENE_MODE_ACTION
                }
                
                camera?.parameters = it
            }
            
            // 设置预览方向
            camera?.setDisplayOrientation(0)
            
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "相机初始化失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
    
    private fun getFrontCameraId(): Int {
        val numberOfCameras = Camera.getNumberOfCameras()
        for (i in 0 until numberOfCameras) {
            val info = Camera.CameraInfo()
            Camera.getCameraInfo(i, info)
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                return i
            }
        }
        // 如果没有前置摄像头，使用默认摄像头
        return 0
    }
    
    private fun startRecording() {
        if (!checkPermissions()) {
            return
        }
        
        if (camera == null) {
            Toast.makeText(this, "相机未初始化", Toast.LENGTH_SHORT).show()
            return
        }
        
        try {
            // 准备MediaRecorder
            prepareMediaRecorder()
            
            // 开始录制
            mediaRecorder?.start()
            
            isRecording = true
            recordingStartTime = System.currentTimeMillis()
            viewModel.startRecording()
            
            // 显示录制状态
            binding.recordingIndicator.visibility = View.VISIBLE
            binding.recordingTimeText.visibility = View.VISIBLE
            binding.recordHintText.text = "录制中..."
            
            // 开始计时
            handler.post(recordingRunnable)
            
            // 改变按钮外观
            binding.recordButtonInner.setBackgroundResource(R.drawable.record_button_recording)
            
            Toast.makeText(this, "开始录制", Toast.LENGTH_SHORT).show()
            
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "录制失败: ${e.message}", Toast.LENGTH_LONG).show()
            
            // 录制失败时重置状态
            isRecording = false
            binding.recordingIndicator.visibility = View.GONE
            binding.recordingTimeText.visibility = View.GONE
            binding.recordHintText.text = "录制失败，请重试"
            binding.recordButtonInner.setBackgroundResource(R.drawable.record_button_inner)
            
            // 释放MediaRecorder
            try {
                mediaRecorder?.reset()
                mediaRecorder?.release()
                mediaRecorder = null
            } catch (e2: Exception) {
                e2.printStackTrace()
            }
        }
    }
    
    private fun stopRecording() {
        if (!isRecording) return
        
        try {
            // 停止录制
            mediaRecorder?.stop()
            mediaRecorder?.reset()
            mediaRecorder?.release()
            mediaRecorder = null
            
            // 重新启动相机预览
            camera?.startPreview()
            
            isRecording = false
            viewModel.stopRecording()
            
            // 隐藏录制状态
            binding.recordingIndicator.visibility = View.GONE
            binding.recordingTimeText.visibility = View.GONE
            binding.recordHintText.text = "录制完成"
            
            // 停止计时
            handler.removeCallbacks(recordingRunnable)
            
            // 恢复按钮外观
            binding.recordButtonInner.setBackgroundResource(R.drawable.record_button_inner)
            
            // 显示发布按钮
            binding.publishButton.visibility = View.VISIBLE
            
            Toast.makeText(this, "录制完成", Toast.LENGTH_SHORT).show()
            
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "停止录制失败: ${e.message}", Toast.LENGTH_LONG).show()
            
            // 即使停止失败，也要重置状态
            isRecording = false
            binding.recordingIndicator.visibility = View.GONE
            binding.recordingTimeText.visibility = View.GONE
            binding.recordHintText.text = "录制异常，请重试"
            binding.recordButtonInner.setBackgroundResource(R.drawable.record_button_inner)
            
            // 停止计时
            handler.removeCallbacks(recordingRunnable)
            
            // 强制释放MediaRecorder
            try {
                mediaRecorder?.reset()
                mediaRecorder?.release()
                mediaRecorder = null
            } catch (e2: Exception) {
                e2.printStackTrace()
            }
            
            // 重新启动相机预览
            try {
                camera?.startPreview()
            } catch (e2: Exception) {
                e2.printStackTrace()
            }
        }
    }
    
    private fun prepareMediaRecorder() {
        // 创建输出文件
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val fileName = "VIDEO_$timeStamp.mp4"
        val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
        outputFile = File(storageDir, fileName)
        
        // 创建MediaRecorder
        mediaRecorder = MediaRecorder()
        
        try {
            // 设置录制源
            mediaRecorder?.setVideoSource(MediaRecorder.VideoSource.CAMERA)
            mediaRecorder?.setAudioSource(MediaRecorder.AudioSource.MIC)
            
            // 使用VideoRecorderConfig配置录制质量
            if (!VideoRecorderConfig.configureQuality(mediaRecorder!!)) {
                throw IOException("无法配置录制质量")
            }
            
            // 设置输出文件
            mediaRecorder?.setOutputFile(outputFile?.absolutePath)
            
            // 设置预览显示
            mediaRecorder?.setPreviewDisplay(binding.cameraPreview.holder.surface)
            
            // 设置录制方向
            mediaRecorder?.setOrientationHint(0)
            
            // 设置录制时长限制（可选，防止录制时间过长）
            // mediaRecorder?.setMaxDuration(60000) // 60秒
            
            // 设置最大文件大小（可选，防止文件过大）
            // mediaRecorder?.setMaxFileSize(100 * 1024 * 1024) // 100MB
            
            mediaRecorder?.prepare()
            
        } catch (e: IOException) {
            e.printStackTrace()
            throw e
        }
    }
    
    private fun updateRecordingTime() {
        val elapsedTime = System.currentTimeMillis() - recordingStartTime
        val seconds = TimeUnit.MILLISECONDS.toSeconds(elapsedTime)
        val minutes = TimeUnit.SECONDS.toMinutes(seconds)
        val remainingSeconds = seconds % 60
        
        val timeText = String.format("%02d:%02d", minutes, remainingSeconds)
        binding.recordingTimeText.text = timeText
    }
    
    private fun updateRecordingUI(state: RecordingState) {
        when (state) {
            is RecordingState.Idle -> {
                // 空闲状态，不需要特殊处理
            }
            is RecordingState.Recording -> {
                // 录制中状态
            }
            is RecordingState.Recorded -> {
                // 录制完成状态
                // 将录制的文件路径传递给ViewModel
                outputFile?.let { file ->
                    viewModel.setVideoPath(file.absolutePath)
                }
            }
        }
    }
    
    private fun updatePublishUI(state: PublishState) {
        when (state) {
            is PublishState.Idle -> {
                binding.publishProgressBar.visibility = View.GONE
            }
            is PublishState.Publishing -> {
                binding.publishProgressBar.visibility = View.VISIBLE
                binding.publishButton.isEnabled = false
                binding.publishButton.text = "发布中..."
            }
            is PublishState.Success -> {
                binding.publishProgressBar.visibility = View.GONE
                binding.publishButton.isEnabled = true
                binding.publishButton.text = "发布"
                Toast.makeText(this, "视频发布成功！", Toast.LENGTH_LONG).show()
                
                // 发布成功后重置状态
                viewModel.resetState()
                binding.publishButton.visibility = View.GONE
                binding.recordHintText.text = "长按录制"
                
                // 删除临时文件
                outputFile?.delete()
                outputFile = null
            }
            is PublishState.Error -> {
                binding.publishProgressBar.visibility = View.GONE
                binding.publishButton.isEnabled = true
                binding.publishButton.text = "发布"
                Toast.makeText(this, "发布失败: ${state.message}", Toast.LENGTH_LONG).show()
            }
        }
    }
    
    private fun showPublishDialog() {
        // 这里可以显示一个对话框让用户输入标题和描述
        // 暂时使用默认值直接发布
        viewModel.publishVideo(title = "我的视频", caption = "用IVideo录制的精彩视频")
    }
    
    private fun checkPermissions(): Boolean {
        val permissions = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        
        val permissionsToRequest = mutableListOf<String>()
        
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(permission)
            }
        }
        
        if (permissionsToRequest.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                permissionsToRequest.toTypedArray(),
                CAMERA_PERMISSION_REQUEST
            )
            return false
        }
        
        return true
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        when (requestCode) {
            CAMERA_PERMISSION_REQUEST -> {
                if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                    Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show()
                    // 权限授予后初始化相机
                    initializeCamera()
                } else {
                    Toast.makeText(this, "需要相机权限才能录制视频", Toast.LENGTH_LONG).show()
                }
            }
        }
    }
    
    private fun releaseCamera() {
        try {
            camera?.stopPreview()
            camera?.release()
            camera = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(recordingRunnable)
        releaseCamera()
        
        // 释放MediaRecorder
        try {
            mediaRecorder?.stop()
            mediaRecorder?.reset()
            mediaRecorder?.release()
            mediaRecorder = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}